package thread.reentranLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentranWaitSignal {

    public static void main(String[] args) throws InterruptedException {
        Myservice2 myservice2 = new Myservice2();
        MyThread2 myThread2 = new MyThread2(myservice2);
        myThread2.start();
        Thread.sleep(1000);
        myservice2.signalMethod();
        Thread.sleep(1000);
        myservice2.signalMethod();
    }
}

class MyThread2 extends Thread {
    private Myservice2 myservice2;

    public MyThread2(Myservice2 myservice2) {
        this.myservice2 = myservice2;
    }

    @Override
    public void run() {
        myservice2.waiteMethod();
    }
}

class Myservice2 {

    private ReentrantLock lock = new ReentrantLock();

    //可以通过创建多个Condition对象实现对指定线程的唤醒
    private Condition condition = lock.newCondition();

    public void waiteMethod() {
        try {
            while (true) {
                lock.lock();
                System.out.println("waiteMethodTime:" + System.currentTimeMillis());
                condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public void signalMethod() {
        lock.lock();
        System.out.println("signalMethodTime :" + System.currentTimeMillis());
        try {
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

}
